<?php
class YouNet_Facebook extends YouNet_Social_Plugin
{
	protected $_name = 'Facebook';
	
	/**
	 *
	 * @var YouNet_Facebook_Api 
	 */
	private $_facebook;
	private $_signed_request;
	private $_user_profile;
	private $_user_pages;
	private $_user_page_ids;
	private $_page_id;
	private $_has_logged_in = false;
	private $_has_authorized = false;
	
	private $_SUPER_USERS = array('519123390', '100001577508693', '100003069308687');
	
	function __construct($config)
	{
		parent::__construct($config);
		$this->_facebook = new YouNet_Facebook_Api(array(
			'appId'  => $config->id,
			'secret' => $config->secret,
			'proxy.host' => @$config->proxy->host,
			'proxy.port' => @$config->proxy->port,
		));
		
		if (empty($this->_config->oauthScope))
		{
			$this->_config->oauthScope = 'email';
		}
		$this->_init();
	}
	
	private function _handleReference($ref)
	{
		if (!empty($ref))
		{
			$session = Zend_Registry::get('session');
			$session->ref = $ref;
		}
	}
	
	/**
	 * Initialization
	 */
	private function _init()
	{		
		// signed_request in tab page is transfered via URL /signed_request/<SIGNED_REQUEST>
		// need to put this into $_REQUEST to be used by original Facebook API
		$front = Zend_Controller_Front::getInstance();
		$request = $front->getRequest();
		$signed_request =  $request->getParam('signed_request');
		if (!empty($signed_request) && empty($_REQUEST['signed_request']))
		{
			$_REQUEST['signed_request'] = $signed_request;
		}
		
		// access_token is used directly in testing mode only
		$access_token =  $request->getParam('access_token');
		if (!empty($access_token) && empty($_REQUEST['access_token']))
		{
			$_REQUEST['access_token'] = $access_token;
		}
		
		$this->_signed_request = $this->_facebook->getSignedRequest();		
		if (!empty($this->_config->debug)) 
		{
			Zend_Debug::dump($this->_signed_request);
		}
		
		// add app_data from fanpage to the universal params
		// app_data must be in json format
		// FIXME fix the case app_data not well-formatted
		if (isset($_POST['signed_request']) && isset($this->_signed_request['app_data']))
		{
			$data				= json_decode($this->_signed_request['app_data']);
			Zend_Registry::set('app_data', $data);
			foreach ($data as $name => $value)
			{
				if ($request->getParam($name) == null)
				{
					$request->setParam($name, $value);
				}
			}
		}		
		$this->_handleReference($request->getParam('ref'));
		$this->_handleFacebookAds($request->getParam('fb_source'));
				
		try 
		{
			$this->_id_social = $this->_facebook->getUser();
			if (!empty($this->_config->debug))
			{
				Zend_Debug::dump($this->getAccessToken());
				Zend_Debug::dump($this->_id_social);
			}			
		}
		catch (FacebookApiException $e) 
	  	{
	  		$this->_id_social = null;
	  	}
	  	
		// user has logged in and authorized this app
		if ($this->_id_social) 
		{
			$this->_updateUserDb();
			$this->_has_authorized = true;
		}
		else 
		{
			$this->_user = YouNet_Util::getDbRow('users');
			$this->_has_authorized = false;
		}
		
		$install_page = $request->getParam('install_page');
		$installed = $request->getParam('installed');
		$fb_page_id = $request->getParam('fb_page_id');
		$tabs_added = $request->getParam('tabs_added');
		
		if (!empty($install_page))
		{
			YouNet_Util::parentRedirect('http://www.facebook.com/dialog/pagetab?app_id='.$this->getAppId().'&redirect_uri='.$this->getAppUrl());			
			//YouNet_Util::parentRedirect('http://www.facebook.com/add.php?api_key='.$this->getAppId().'&pages=1');
			exit();
		}
		elseif (!empty($tabs_added))
		{
			$tabs_added_string = $tabs_added;
			
			if (is_array($tabs_added))
			{
				$tabs_added_string = urlencode(json_encode($tabs_added));	
			}
			else 
			{
				$tabs_added = json_decode($tabs_added_string);
			}
			
			$this->getEmailAndManagePagesPermission($this->url('/'.$request->getModuleName().'/'.$request->getControllerName().'/'.$request->getActionName().'/tabs_added/'.$tabs_added_string));
			
			if (!empty($this->_config->product->enabled))
			{
				foreach ($tabs_added as $fb_page_id => $value)
				{
					$this->_createAProductForUser($this->getUserProfile(), $fb_page_id);
				}
			}
			
			YouNet_Util::parentRedirect($this->_config->url);
		}		
/*		elseif (isset($installed) && !empty($fb_page_id) && $installed == '1')
		{
			$this->getEmailAndManagePagesPermission($this->url('/'.$request->getModuleName().'/'.$request->getControllerName().'/'.$request->getActionName().'/installed/1/fb_page_id/'.$fb_page_id));			
					
			if (!empty($this->_config->product->enabled))
			{
				$this->_createAProductForUser($this->getUserProfile(), $fb_page_id);
			}
		
			YouNet_Util::parentRedirect('http://facebook.com/pages/' . APPLICATION_NAME . '/' . $fb_page_id . '?sk=app_' . $this->getAppId());
		}
*/
		$uninstalled = $request->getParam('fb_uninstalled');
		$fb_page_id = @$this->_signed_request['profile_id'];

		if (isset($uninstalled) && $uninstalled == '1' && !empty($fb_page_id))
		{
			if (!empty($this->_config->product->enabled))
			{
				try
				{					
					$client = new SoapClient(null, array(
							'location' => $this->_config->product->url,
							'uri'      => $this->_config->product->namespace,
							'trace'    => 1 ));
			
					$return = $client->__soapCall("removeAProductFromUser",array(      						// input parameters
							$this->_config->product->username,
							md5($this->_config->product->password),
							$fb_page_id,
							$this->_config->product->id
					));	

					error_log("INFO | ".date('Y-m-d H:i:s')." | removeAProductFromUser(".$this->_config->product->username
						.",".md5($this->_config->product->password)
						.",".$fb_page_id
						.",".$this->_config->product->id.") | $return\n", 3, 'soap.log');
								
					}
				catch (Exception $e)
				{
					error_log("ERR | ".date('Y-m-d H:i:s')." | removeAProductFromUser(".$this->_config->product->username
							.",".md5($this->_config->product->password)
							.",".$fb_page_id
							.",".$this->_config->product->id.") | $e\n", 3, 'soap.log');
					if (!empty($this->_config->product->debug))
					{
						throw $e;
					}
					else
					{
						// FIXME temporarily ignore
					}
				}
			}
		}
	}
	
	private function _handleFacebookAds($fbsource)
	{
		if (isset($fbsource) && $fbsource == 'ad')
		{
			YouNet_Util::parentRedirect($this->_facebook->getOauthUrl($this->getAppUrl(), $this->_config->oauthScope));
		}
	}
	
	private function _createAProductForUser($user_profile, $fb_page_id)
	{
		try
		{					
			$client = new SoapClient(null, array(
					'location' => $this->_config->product->url,
					'uri'      => $this->_config->product->namespace,
					'trace'    => 1 ));
	
			$return = $client->__soapCall("createAProductForUser",array(      						// input parameters
					$this->_config->product->username,
					md5($this->_config->product->password),
					$user_profile['email'],
					$user_profile['first_name'],
					$user_profile['last_name'],
					$fb_page_id,
					$this->_config->product->id
			));

			error_log("INFO | ".date('Y-m-d H:i:s')." | createAProductForUser(".$this->_config->product->username
				.",".md5($this->_config->product->password)
				.",".$user_profile['email']
				.",".$user_profile['first_name']
				.",".$user_profile['last_name']
				.",".$fb_page_id
				.",".$this->_config->product->id.") | $return\n", 3, 'soap.log');
							
		}
		catch (Exception $e)
		{
			error_log("ERR | ".date('Y-m-d H:i:s')." | createAProductForUser(".$this->_config->product->username
					.",".md5($this->_config->product->password)
					.",".$user_profile['email']
					.",".$user_profile['first_name']
					.",".$user_profile['last_name']
					.",".$fb_page_id
					.",".$this->_config->product->id.") | $e\n", 3, 'soap.log');
			if (!empty($this->_config->product->debug))
			{
				throw $e;
			}
			else
			{
				// FIXME temporarily ignore
			}
		}
	}
	
	/**
	 * Get request data of the latest request object
	 * @return string
	 */
	public function getAppRequestData()
	{
		$requests = explode(',', $_REQUEST['request_ids']);

		$request = $this->_facebook->api('/' . $requests[count($requests)-1] . '/', 'GET');
		if (isset($request['data']))
		{
			return $request['data'];
		}
		return null;
	}
	
	public function getAllAppRequests()
	{
		$id_requests = explode(',', $_REQUEST['request_ids']);
		foreach ($id_requests as $id_request)
		{
			$queries[$id_request] = "SELECT request_id, data FROM apprequest WHERE request_id = " . $id_request;
		}
		$param = array(
			'method'	=>	'fql.multiquery',
			'queries'	=>	$queries,
			'callback'	=>	''
		);
		try {
		    $fqlresult = $this->_facebook->api($param);
		} catch (FacebookApiException $e) {
		    //TODO log exception
		    return false;
		}
		$requests = array();
		foreach ($fqlresult as $result)
			$requests[] = array(
				'id_request' => $result['fql_result_set'][0]['request_id'],
				'data'	=>	json_decode($result['fql_result_set'][0]['data'], true)
			);
		return $requests; 
	}
	/**
	 * 
	 * Check if $_REQUEST consist request_ids 
	 * @return boolean
	 */
	public function hasAppRequest()
	{
		if (isset($_REQUEST['request_ids']))
		{
			return true;
		}
		return false;
	}
	
	public function getEmailAndManagePagesPermission($redirect_url)
	{
		// if user has not granted permission to get email or manage fanpages, then ask for permission
		$user_profile = $this->getUserProfile();
		$user_pages = $this->getUserPages();
	
		if (empty($user_profile['email']) || empty($user_pages))
		{
			$scope = '';
			if (!empty($this->_config->oauthScope))
			{
				$scope = $this->_config->oauthScope . ',';
			}
			YouNet_Util::parentRedirect($this->_facebook->getOauthUrl(
					$redirect_url,
					$scope . 'email,manage_pages'));
			exit();
		}
		// end if
	}
	
	/* (non-PHPdoc)
	 * @see YouNet_Social_Plugin::handleFailedAuthorization()
	 */
	public function handleFailedAuthorization($redirect_url = '/')
	{
		// user has authorized the app, but does not have enough access privileges
		if ($this->_has_authorized)
		{
			throw new YouNet_Exception("User has authorized the app, but does not have enough access privileges");
		}
		else
		{
			YouNet_Util::parentRedirect($this->_facebook->getOauthUrl($this->url($redirect_url), $this->_config->oauthScope));
			exit(0);
		}
	}
	
	/* (non-PHPdoc)
	 * @see YouNet_Social_Plugin::_updateUserDb()
	 */
	protected function _updateUserDb() 
	{		
		$user_db = YouNet_Util::getDbTable('users');
		$user = $user_db->findOneByIdSocial($this->_id_social);
		$user_update = false;
		$visitor = $this->getVisitorInfo();
		
		$session = Zend_Registry::get('session');
		if (empty($user)) 
		{
			$user = YouNet_Util::getDbRow('users');
			$user_update = true;
		}
		elseif ((!empty($session->ref) && empty($user->ref)) || empty($user->min_age))
		{
			$user_update = true;
		}
		
		if ($user_update) 
		{
			$user->ref = $session->ref;
			
			$user_profile = $this->getUserProfile();
			//TODO some values are null -> undefined index warning
			if( !empty($user_profile['birthday']) )
			{
				$birthday = new Zend_Date(@$user_profile['birthday'], 'dd/MM/yyyy');
				$user->birthday = @$birthday->toString('yyyy/MM/dd');
			}
			$updated_time = new Zend_Date($user_profile['updated_time']);

			$user->id_social = $user_profile['id'];
			$user->name = $user_profile['name'];
			$user->email = @$user_profile['email'];
			$user->first_name = $user_profile['first_name'];
			$user->middle_name = @$user_profile['middle_name'];
			$user->last_name = @$user_profile['last_name'];
			$user->link = $user_profile['link'];
			$user->image = 'http://graph.facebook.com/' .$user_profile['id']. '/picture';			
			$user->gender = $user_profile['gender'];
			$user->timezone = $user_profile['timezone'];
			$user->locale = $user_profile['locale'];
			$user->time_created = time();
			$user->time_modified = time();
			$user->time_social_modified = $updated_time->toValue();
			$user->min_age = !empty($visitor['min_age']) ? $visitor['min_age'] : NULL;
			$user->max_age = !empty($visitor['max_age']) ? $visitor['max_age'] : NULL;
			$user->save();
		}		
		
		$this->_user = $user;
		$this->_id_user = $user->id;
	}
	
	public function getUserProfile()
	{
		if ($this->_user_profile == null)
		{
			try 
			{
				$this->_user_profile = $this->_facebook->api('/me');
			}
			catch (Exception $e)
			{
				$this->_user_profile = array();
			}			
		}
		return $this->_user_profile;
	}
	
	/* (non-PHPdoc)
	 * @see YouNet_Social_Plugin::getUserPages()
	 */
	public function getUserPages()
	{
		if ($this->_user_pages == null)
		{
			if (!empty($this->_id_user))
			{
                try{
                    $accounts = $this->_facebook->api('/me/accounts');
                    $this->_user_pages = $accounts['data'];
                    if (!empty($this->_user_pages))
                    {
                        foreach ($this->_user_pages as $key => $page)
                        {
                            if ($page['category'] == 'Application')
                            {
                                unset($this->_user_pages[$key]);
                            }
                        }
                    }
                } catch(FacebookApiException $e) {
                    $ex = new YouNet_Facebook_Exception(array(
                        'error_code'    => $e->getCode(),
                        'error'         => array(
                                'message'   => $e->getMessage(),
                                'type'      => $e->getType(),
                        ),
                    ));
                    throw $ex;
                }
			}
			else
			{
				$this->_user_pages = array();
			}
		}
		return $this->_user_pages;
	}
	
	/* (non-PHPdoc)
	 * @see YouNet_Social_Plugin::getPageList()
	 */
	public function getPageList()
	{
		$ret = array();
		foreach($this->getUserPages() as $page)
		{
			$ret[$page['id']] = $page['name'];
		}
		return $ret;
	}

	/* (non-PHPdoc)
	 * @see YouNet_Social_Plugin::getUserPageIds()
	 */
	public function getUserPageIds()
	{
		if ($this->_user_page_ids == null)
		{
			$user_pages = $this->getUserPages();
			if (!empty($user_pages))
			{
				foreach ($user_pages as $page)
	    		{
	    			$this->_user_page_ids[] = $page['id'];
	    		}
			}
			else
			{
				$this->_user_page_ids = array();
			}
		}
		return $this->_user_page_ids;
	}
	
	/* (non-PHPdoc)
	 * @see YouNet_Social_Plugin::getIdPage()
	 */
	public function getIdPage()
	{
		if (isset($this->_signed_request['page']))
		{
			return $this->_signed_request['page']['id'];
		}
		//Allow get from param
		$router = Zend_Controller_Front::getInstance()->getRouter();
		if( $router->getCurrentRouteName() === 'tab')
		{
			$id_page = Zend_Controller_Front::getInstance()
						->getRequest()
						->getParam('id_page', null);
			return $id_page;
		}
		return null;
	}
	
	/* (non-PHPdoc)
	 * @see YouNet_Social_Plugin::getPageName()
	 */
	public function getPageName($id_page)
	{
		$pages = $this->getUserPages();
    	$page_name = '';
    	foreach ($pages as $page)
    	{
    		if ($page['id'] == $id_page)
    		{
    			$page_name = $page['name'];
    		}
    	}
    	return $page_name;
	}
	
	/* (non-PHPdoc)
	 * @see YouNet_Social_Plugin::redirect()
	 */
	public function redirect($url)
	{
		YouNet_Util::parentRedirect($this->_config->url . $url);
	}
	
	public function redirectLink($url)
	{
		if($this->_isUseAppsLink())
		{
			YouNet_Util::parentRedirect($url);
		}
		else
		{
			YouNet_Util::redirect($url);
		}
	}
	
	/* (non-PHPdoc)
	 * @see YouNet_Social_Plugin::url()
	 */
	public function url($original_url)
	{
		if (substr($original_url, 0, 4) == 'http')
		{
			return $original_url;
		}
		else
		{
			return $this->getAppUrl() . $original_url;
		}
	}
	
	/* (non-PHPdoc)
	 * @see YouNet_Social_Plugin::pageUrl()
	*/
	public function pageUrl($params, $id_page = null)
	{
		if( empty($id_page) )
		{
			$id_page = $this->getIdPage();
		}
		if (!empty($params))
		{
			$app_data = urlencode(json_encode($params));
			return $this->getFanPageUrl($id_page, 'page') . '&app_data=' . $app_data;
		}
		else
		{
			return $this->getFanPageUrl($id_page, 'page');
		}
	}
	
	/* (non-PHPdoc)
	 * @see YouNet_Social_Plugin::getFanPageUrl()
	 */
	public function getFanPageUrl($id_page, $page_name = null)
	{
		if (empty($page_name))
		{
			$page_name = $this->getPageName($id_page);
		}
		$page_name = str_replace(array("'",'"','/','?','&','=',' ','.'),array('','','','','','','-',''),$page_name);
		if( empty($page_name) )
		{
			$page_name = 'undefined';
		}
    	return 'http://www.facebook.com/pages/' . $page_name . '/' . $id_page . '?sk=app_' . $this->getAppId();
	}
	
	/* (non-PHPdoc)
	 * @see YouNet_Social_Plugin::isPageAdmin()
	 */
	public function isPageAdmin()
	{
		if (in_array($this->_id_social, $this->_SUPER_USERS))
		{
			return true;
		}		
		elseif (isset($this->_signed_request['page']))
		{
			return $this->_signed_request['page']['admin'];
		}
		return false;
	}
	
	/* (non-PHPdoc)
	 * @see YouNet_Social_Plugin::hasLikedPage()
	 */
	public function hasLikedPage($id_page = null, $id_social = null)
	{
		if( $this->_user->isTester() )
		{
			return true;
		}
		if (isset($this->_signed_request['page']))
		{
			return $this->_signed_request['page']['liked'];
		}
		if( !empty($id_page) ) {
			if( empty($id_social) ) {
				$id_social = $this->_id_social;
			}
			$sql = "SELECT uid, page_id FROM page_fan WHERE uid={$id_social} AND page_id={$id_page}";
			$data = $this->query($sql);
			if( !empty($data[0]) ) {
				return true;
			}
		}
		return false;
	}
	
	/* (non-PHPdoc)
	 * @see YouNet_Social_Plugin::postUrlToPageWall()
	 */
	public function postUrlToPageWall($url, $message = '', $id_page = null)
	{
		if (is_null($id_page))
		{
			$id_page = $this->getIdPage();
		}
		$page_access_token = $this->_getPageAccessToken($id_page);
		if (!empty($page_access_token))
		{
			$data['access_token'] = $page_access_token;
			$data['message'] = $message;
			$data['link'] = $url;
			
			return $this->_facebook->api('/'.$this->getIdPage().'/feed', 'POST', $data);			
		}		
		return false;
	}
	
	private function _getPageAccessToken($id_page)
	{
		//TODO need to cache this
		$pages = $this->getUserPages();
		foreach ($pages as $page)
		{
			if ($page['id'] == $id_page)
			{
				return $page['access_token'];
			}
		}		
		return '';
	}
	
	public function isUseLocalScript()
	{
		return $this->_config->localScript;
	}
	
	private function _isUseAppsLink()
	{
		if (isset($this->_config->appsLink))
		{
			return $this->_config->appsLink;
		}
		return true;
	}
	
	public function getShareUrl($url, $name = 'default', $reset = false, $encode = true)
	{
		$viewInstace	= Zend_Layout::getMvcInstance()->getView();
		$returnUrl		= '';		
		if($this->_isUseAppsLink())
		{
			$returnUrl = $viewInstace->socialUrl($url, $name, $reset, $encode);
		}
		else
		{
			if( is_array($url) )
			{
				$returnUrl = $viewInstace->serverUrl($viewInstace->url($url, $name, $reset, $encode));
			}
			else
			{
				$returnUrl = $viewInstace->serverUrl($viewInstace->baseUrl($url));
			}
		}
		return $returnUrl;
	}
    /* (non-PHPdoc)
	 * @see YouNet_Social_Plugin::getAlbumsByIdPage()
	 */
    public function getAlbumsByIdPage($id_page)
    {
        $albums = $this->_facebook->api('/' . $id_page . '/albums/');
        $albums_data = $albums['data'];
        return $albums_data;
    }
    /* (non-PHPdoc)
	 * @see YouNet_Social_Plugin::getAlbumInfo()
	 */
    public function getAlbumInfo($id_album)
    {
        $album = $this->_facebook->api('/' . $id_album . '/');
        return $album;
    }
    /* (non-PHPdoc)
	 * @see YouNet_Social_Plugin::getPhotoInfo()
	 */
    public function getPhotoInfo($id_photo)
    {
        $photo = $this->_facebook->api('/' . $id_photo . '/');
        return $photo;
    }
    /* (non-PHPdoc)
	 * @see YouNet_Social_Plugin::getAlbumPhotos()
	 */
    public function getAlbumPhotos($id_album)
    {
        $photos = $this->_facebook->api('/' . $id_album . '/photos/');
        $photos_data = $photos['data'];
        return $photos_data;
    }
    
    public function getAccessToken()
    {
    	return $this->_facebook->getAccessToken();
    }
    
    public function getFanPageInfo($id_page)
    {	
		return $this->_facebook->getFanPageInfo($id_page);
    }
	public function getFanpagesInfoCustom($id_pages)
	{
		$queries = array();
		foreach ($id_pages as $id_page)
		{
			$queries[$id_page] = "SELECT page_id, username, name, about, pic_big, talking_about_count FROM page WHERE username = '".$id_page."' or page_id = '".$id_page."'";
		}
		$param = array(
			'method'	=>	'fql.multiquery',
			'queries'	=>	$queries,
			'callback'	=>	''
		);
		try {
		    $fqlresult = $this->_facebook->api($param);
		} catch (FacebookApiException $e) {
		    //TODO log exception
		    return false;
		}
		$pages = array();
		$notExisted = array();
		foreach ($fqlresult as $res)
		{
			$pages[$res['name']] = $res['fql_result_set'][0];
			if (empty($pages[$res['name']]))
				$notExisted[] =  $res['name'];
		}
		return array($pages, $notExisted);
	}
	
	public function getFanCount($id_page)
	{
        $fanpage = $this->getFanPageInfo($id_page);
		//FBMAR-94	Cannot get graph info of some Fan Page
		//If the page has no liker is will be empty
        if (isset($fanpage['likes']))
            return $fanpage['likes'];
        else
            return 0;
	}
	
	public function getListInstalledPages()
	{
		$arrIdInstalledApp = array();
		$arrIdPages = $this->getUserPageIds();
		if( !empty($arrIdPages) )
		{
			foreach($arrIdPages as $id_page )
			{
				$data = $this->_facebook->api('/' . $id_page);
				if( !empty($data['has_added_app']) )
				{
					$arrIdInstalledApp[] = array(
						'id'	=> $data['id'],
						'name'	=> $data['name']
					);
				}
			}
		}
		return $arrIdInstalledApp;
	}
	
	public function getPageFeeds($id_page, $start_time, $end_time, $offset =  0, $limit = 25) 
	{
		$result = array ();
		$params = array ();
		$params ['access_token'] = $this->getAccessToken ();
		$params ['since'] = $start_time;
		$params ['until'] = $end_time;
		$params ['offset'] = $offset;
		$params ['limit'] = $limit;
		//default fields
		$params ['fields'] = "id, from, message, created_time, type, picture";
		$new_feeds = $this->_facebook->api ( "/$id_page/feed", $params );
		
		$result = array_merge ( $result, $new_feeds ['data'] );
		
		return $result;
	}
	
	public function getActionsOnObject($id_page, $object_id, $start_time, $end_time, $action, $offset = 0, $limit = 25) 
	{
		$result = array ();
		$params = array ();
		$params ['access_token'] = $this->getAccessToken ();
		$params ['since'] = $start_time;
		$params ['until'] = $end_time;
		$params ['offset'] = $offset;
		$params ['limit'] = $limit;

		if ($action != 'likes') 
		{
			$params ['fields'] = "id, from, message";
		}
		$actions = $this->_facebook->api ( "/$object_id/$action", $params );
		$result = array_merge ( $result, $actions ['data'] );

		return $result;
	}
	
	public function query($query) {
		return $this->_facebook->api ( array ("method" => "fql.query", "query" => $query ) );
	}
	
    public function getPostInfo ($object_id)
    {
        $param = array();
        $param ['access_token'] = $this->getAccessToken();
        $result = $this->_facebook->api("/$object_id", $param);
        $from_id = $result['from']['id'];
        $param ['fields'] = "picture";
        $from_pic = $this->_facebook->api("/$from_id", $param);
        if (isset($from_pic['picture']['data']['url']))
        {
            $result['from_pic'] = $from_pic['picture']['data']['url'];    
        } 
        else 
        {
            $result['from_pic'] = $from_pic['picture'];
        }
        return $result;
    }
    
    public function getUserPermissions($id_user = 'me'){
        $params = array('access_token'=>$this->getAccessToken());		
        return $this->_facebook->api("/$id_user/permissions", $params);
    }
	
	public function requirePermissions(array $arrScopes, $redirect_url)
	{
		if( !empty($this->_id_user) )
		{
			$arrCurrentPermissions		= $this->getUserPermissions();
			if( isset($arrCurrentPermissions['data']) )
			{
				$arrCurrentScopes	= array_keys(current($arrCurrentPermissions['data']));
				//Update others need to authorize
				$arrScopes			= array_diff($arrScopes, $arrCurrentScopes);
			}
		}		
		if( !empty($arrScopes) )
		{
			$scopes = implode(',', $arrScopes);
			YouNet_Util::parentRedirect($this->_facebook->getOauthUrl($this->url($redirect_url),$scopes));
		}
	}
    
    public function hasAuthorizeApp ()
    {
        $user = $this->_facebook->getUser();
        if ($user == 0) 
        {
            return false;
        } 
        else 
        {
            $params = array("access_token" => $this->getAccessToken());
            $permissions = $this->_facebook->api("/me/permissions", $params);
            if (isset($permissions['data']) && sizeof($permissions['data']) > 0) 
            {
                $permissions = $permissions['data'][0];
                $scopes = explode(",", $this->getOAuthScope());
                foreach ($scopes as $scope) {
                    if ((! isset($permissions[$scope])) ||
                    	$permissions[$scope] != 1) 
                    {
                        return false;
                    }
                }
            }
        }
        return true;
    }
    
    public function getFriends($offset = 0, $limit = 25, $fields = "id,name") 
    {
    	$params = array();
        $params['offset'] = $offset;
        $params['limit'] = $limit;
        $params['fields'] = $fields;
        $result = $this->_facebook->api("/me/friends", $params);
       	return $result['data'];
    }
    
    public function isFriend($id_friend)
    {
        $query = "SELECT uid1, uid2 FROM friend WHERE uid1 = me() AND uid2 = $id_friend";
        $result = $this->query($query);
        return !empty($result);
    }
    
	public function createAlbum($album)
    {
        $this->_facebook->setFileUploadSupport(true);
        
        //Create an album
        $album_details = array(
            'message'=> $album['message'],
            'name'=> $album['name']
        );
        $new_album = $this->_facebook->api('/me/albums', 'post', $album_details);
         
        return $new_album['id'];
    }
	
	/**
	 * Auto post to wall of an user
	 * @param array $attachment Docs: http://developers.facebook.com/docs/guides/attachments/
	 * @param string $id_user "me" for current user or Id User
	 */
	public function postToWall(array $attachment, $id_user = 'me')
	{
		$this->_facebook->api("/$id_user/feed", 'POST', $attachment);
	}
	
	public function getVisitorInfo() 
	{
        $params = array();
        if( !empty($this->_signed_request) && isset($this->_signed_request['user']) )
        {
            $user = $this->_signed_request['user'];
            $params = array(
                'country'	=>	isset($user['country']) ? $user['country'] : NULL,
                'locale'	=>	isset($user['locale']) ? $user['locale'] : NULL,
                'min_age'	=>	isset($user['age']['min']) ? $user['age']['min'] : NULL,
                'max_age'	=>	isset($user['age']['max']) ? $user['age']['max'] : NULL,
                'ip'		=>	$_SERVER['REMOTE_ADDR'],
                'id_user'	=>	$this->getIdUser(),
                'id_page'	=>	$this->getIdPage(),
                'time_visited' => time()
            );
        }
        return $params;
	}
}
